﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// 消息分发
/// </summary>
public class MsgMgr : MonoBehaviour
{
    public static MsgMgr Instance;

    /// <summary>
    /// 消息列表
    /// </summary>
    private Dictionary<Type, UnityAction<object>> msgDic;
    /// <summary>
    /// 消息队列
    /// </summary>
    private Queue<Msg> msgs;

    public MsgMgr()
    {
        Instance = this;
        msgDic = new Dictionary<Type, UnityAction<object>>();
        msgs = new Queue<Msg>();
    }

    private void Update()
    {
        if (msgs.Count > 0)
        {
            Msg msg = msgs.Dequeue();
            if (msg != null && msg._action != null && msg._obj != null)
            {
                msg._action(msg._obj);
            }
        }
    }

    /// <summary>
    /// 添加事件监听 
    /// </summary>
    /// <param name="name"></param>
    /// <param name="action"></param>
    public void AddListener(Type name, UnityAction<object> action)
    {
        if (!msgDic.ContainsKey(name))
        {
            msgDic.Add(name, action);
        }
        else
        {
            msgDic[name] += action;
        }
    }

    /// <summary>
    /// 添加事件监听 
    /// </summary>
    /// <param name="name"></param>
    /// <param name="action"></param>
    public void RemoveListener(Type name, UnityAction<object> action)
    {
        if (msgDic.ContainsKey(name))
        {
            msgDic[name] -= action;
        }
        else
        {
            msgDic.Remove(name);
        }
    }

    /// <summary>
    /// 清除所有的监听者
    /// </summary>
    public void ClearAllListeners()
    {
        msgDic.Clear();
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="name"></param>
    /// <param name="args"></param>
    public void SendMsg(Type name, object obj)
    {
        UnityAction<object> action;
        if (msgDic.TryGetValue(name, out action))
        {
            if (action != null)
            {
                //action(obj);
                Msg msg = new Msg(action, obj);
                msgs.Enqueue(msg);
            }
        }
    }
}

/// <summary>
/// 消息
/// </summary>
public class Msg
{
    public UnityAction<object> _action;
    public object _obj;

    public Msg(UnityAction<object> action, object obj)
    {
        _action = action;
        _obj = obj;
    }
}